package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"github.com/mangenotwork/common/conf"
	"github.com/mangenotwork/common/ginHelper"
	"github.com/mangenotwork/common/log"
	"github.com/mangenotwork/common/utils"
	gt "github.com/mangenotwork/gathertool"
	"net/http"
)

type AdminLoginReq struct {
	User     string `json:"user"`
	Password string `json:"password"`
}

type ResponseJson struct {
	Code      int64       `json:"code"` // succeed:0  err:1
	Msg       string      `json:"msg"`
	Date      interface{} `json:"data"`
	TimeStamp int64       `json:"timeStamp"`
}

type AdminLoginResp struct {
	IsOk int `json:"is_ok"` // 1:登录成功  非1:失败
}

type SetAdminTokenReq struct {
	User  string `json:"user"`
	Token string `json:"token"`
}

func Login(c *ginHelper.GinCtx) {
	user := c.PostForm("user")
	password := c.PostForm("password")

	req := &AdminLoginReq{
		User:     user,
		Password: password,
	}
	reqStr, err := json.Marshal(req)
	if err != nil {
		c.APIOutPutError(err, err.Error())
		return
	}

	loginApi, err := conf.YamlGetString("apiUrl")
	if err != nil {
		c.APIOutPutError(err, err.Error())
		return
	}

	loginUrl := loginApi + "/login/admin"

	gtCtx, err := gt.PostJson(loginUrl, string(reqStr))
	if err != nil {
		c.APIOutPutError(err, err.Error())
		return
	}

	resp := &ResponseJson{}
	err = json.Unmarshal([]byte(gtCtx.Json), &resp)
	if err != nil {
		log.Error("gtCtx.Json = ", gtCtx.Json)
		c.APIOutPutError(err, err.Error())
		return
	}

	respData := utils.AnyToMap(resp.Date)
	isOk, ok := respData["is_ok"]
	if !ok || utils.AnyToInt64(isOk) != 1 {
		c.HTML(200, "err.html", gin.H{
			"Title": conf.Conf.Default.App.Name,
			"err":   "账号或密码错误",
		})
		return
	}

	j := utils.NewJWT(conf.Conf.Default.Jwt.Secret, conf.Conf.Default.Jwt.Expire)
	j.AddClaims("name", user)
	token, tokenErr := j.Token()
	if tokenErr != nil {
		log.Error("生成token错误， err = ", tokenErr)
		c.APIOutPutError(tokenErr, tokenErr.Error())
		return
	}

	setToken := &SetAdminTokenReq{
		User:  user,
		Token: token,
	}
	setTokenStr, err := json.Marshal(setToken)
	if err != nil {
		c.APIOutPutError(err, err.Error())
		return
	}
	setTokenUrl := loginApi + "/set/admin/token"
	_, err = gt.PostJson(setTokenUrl, string(setTokenStr))
	if err != nil {
		c.APIOutPutError(err, err.Error())
		return
	}

	c.SetCookie("sing", token, 186400, "/", "", false, true)
	c.SetCookie("user", user, 186400, "/", "", false, true)
	c.Redirect(http.StatusFound, "/home")
	return
}

func Out(c *ginHelper.GinCtx) {
	c.SetCookie("sing", "", 0, "/", "", false, true)
	c.SetCookie("user", "", 0, "/", "", false, true)
	c.Redirect(http.StatusFound, "/login")
}
